package at.fhj.itm10.ticketmaster.beans;

import java.util.Calendar;
import java.util.Map;

import javax.annotation.ManagedBean;
import javax.annotation.PostConstruct;
import javax.faces.bean.RequestScoped;

import at.fhj.itm10.ticketmaster.dao.DAOException;
import at.fhj.itm10.ticketmaster.entities.Order;
import at.fhj.itm10.ticketmaster.entities.Ticket;
import at.fhj.itm10.ticketmaster.services.CartService;
import at.fhj.itm10.ticketmaster.services.OrderService;
import at.fhj.itm10.ticketmaster.services.ServiceFactory;
import at.fhj.itm10.ticketmaster.services.TicketService;

/**
 * @author 	Martin Kropf, Kevin Reinmüller
 * @since	November 2012
 */

@ManagedBean
@RequestScoped
public class OrderBean {

	private Order order;
	private OrderService service;
	private CartService cartService;
	
	/**
	 * initializing Bean
	 */
	public OrderBean() {
		init();
	}
	
	/**
	 * cartservice/orderservice object for order operations
	 */
	@PostConstruct
	public void init() {
		ServiceFactory factory = new ServiceFactory();
		service = factory.getOrderService();
		cartService = factory.getCartService();
	}

	/**
	 * returns Order
	 * 
	 * @return
	 */
	public Order getOrder() {
		return order;
	}
	
	/**
	 * creates new Order and saves it in DB
	 * removes tickets from cart (saveOrder)
	 * creates ticket object for every ticket in cart and saves it in DB
	 * 
	 * @param cust_id
	 */
	public void saveOrder(Long cust_id){
		this.setOrder(new Order(cust_id, Calendar.getInstance().getTime(), Calendar.getInstance().getTime(), true));
		
		cartService.saveOrder(cust_id);
		for (Map.Entry<String, Integer> entry : cartService.showTickets().entrySet()) {
			Ticket ticket_db = new Ticket(order.getId(),Long.parseLong(entry.getKey()),entry.getValue(),Calendar.getInstance().getTime());
			new TicketBean().setTicket(ticket_db);
		}
	}

	/**
	 * Insert new Order in DB
	 * 
	 * @param order
	 * @throws DAOException
	 */
	public void setOrder(Order order) throws DAOException {
		this.order = order;
		
		service.insertOrder(order);
	}
}
